package web

import (
	"AppBigDevops/src/common"
	"AppBigDevops/src/config"
	"AppBigDevops/src/web/middleware"
	"AppBigDevops/src/web/view"
	"github.com/gin-contrib/requestid"
	"github.com/gin-gonic/gin"
	ginprometheus "github.com/zsais/go-gin-prometheus"
	"net/http"
	"time"
)

// 只管启动gin
// view 放到专门的目录下
func StartGin(sc *config.ServerConfig) error {

	gin.SetMode(gin.ReleaseMode)

	// 初始化引擎
	//r := gin.Default()
	r := gin.New()
	r.Use(gin.Recovery())

	// 中间件
	// 传递变量
	varMap := map[string]interface{}{}
	varMap[common.GIN_CTX_CONFIG_LOGGER] = sc.Logger
	varMap[common.GIN_CTX_CONFIG_CONFIG] = sc
	r.Use(middleware.ConfigMiddleware(varMap))

	// 打印耗时
	//r.Use(middleware.TimeCost())

	// request-id
	r.Use(requestid.New())

	// gin-zap
	//r.Use(ginzap.Ginzap(sc.Logger, time.RFC3339, false))
	// 升级版
	// 三个作业：记录，请求id，请求body，header中的token
	r.Use(middleware.NewGinZapLogger(sc.Logger))
	gin.DisableConsoleColor()

	// prometheus中间件  暴露metric
	p := ginprometheus.NewPrometheus("gin")
	p.Use(r)

	// 配置路由
	view.ConfigRouters(r)

	// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
	//return r.Run(sc.HttpAddr)

	// 使用http启动gin
	// http 读写超时参数
	s := &http.Server{
		Addr:    sc.HttpAddr,
		Handler: r,

		ReadTimeout:  time.Second * 15,
		WriteTimeout: time.Second * 15,

		MaxHeaderBytes: 1 << 20,
	}
	return s.ListenAndServe()

}
